iT邦幫忙

0

[C#] Linked List Cycle 解法

c#
  • 分享至 

  • xImage
  •  
       static void Main(string[] args)
       {
           HasCycle();
       }

       public class ListNode
       {
           public int val;
           public ListNode next;
           public ListNode(int x) { val = x; }
       }

       private static void HasCycle()
       {
           //  3 -> 2 -> 0 -> -4
           ListNode head = new ListNode(3);
           head.next = new ListNode(2);
           head.next.next = new ListNode(0);
           head.next.next.next = new ListNode(-4);

           // 使得環 -4 指向 2
           head.next.next.next.next = head.next;

           bool result = HasCycle(head);
           Console.WriteLine(result ? "有環." : "沒環");
           Console.ReadKey();
       }

       public static bool HasCycle(ListNode head)
       {
           if (head == null || head.next == null)
           {
               return false;
           }

           ListNode slow = head;
           ListNode fast = head.next;

           while (slow != fast)
           {
               if (fast == null || fast.next == null)
               {
                   return false;
               }
               slow = slow.next;
               fast = fast.next.next;
           }

           return true;
       }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言